package com.flashphoner.api
{
	import com.adobe.cairngorm.model.IModelLocator;
	import com.flashphoner.Logger;
	import com.flashphoner.api.data.ErrorCodes;
	import com.flashphoner.api.data.PhoneConfig;
	import com.flashphoner.api.management.SoundControl;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.*;
	import flash.media.*;
	import flash.net.*;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.core.Application;
	
	[Bindable]
	public class PhoneModel implements IModelLocator 
	{	
		private var phoneController:PhoneController;
		private var xml:XML;
		private static var phoneModel:PhoneModel
				
		public static function getInstance():PhoneModel {
			if (phoneModel == null){
				phoneModel = new PhoneModel();
			}	
			return phoneModel;				
		}
				
		
		
		public function PhoneModel()
		{	
			super();
			init();
			phoneController = new PhoneController();	
						
		}	
		
		private function init(event:TimerEvent = null):void{
			var loader:URLLoader = new URLLoader();
			var qwe:Object = Application.application.parameters;
			var config:String = "flashphoner.xml";
        	try{
				if (Application.application.parameters != null && Application.application.parameters.config!=null){
					config = Application.application.parameters.config;
				}
        	} catch (e:Error){
        		config = "flashphoner.xml";
        	}       			

			var request:URLRequest = new URLRequest(config);
			loader.load(request);
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,seurityErrorHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			
		}
		
		private function seurityErrorHandler(event:SecurityErrorEvent):void{
			throw new Error(event.toString());
		} 
		
		private function ioErrorHandler(event:IOErrorEvent):void{
			throw new Error(event.toString());
		}
		
		private function onComplete(event:Event):void
			{	
			    var loader:URLLoader = event.target as URLLoader;
			    if (loader != null)
			    {
			        xml = new XML(loader.data);
			        
			        PhoneConfig.SERVER_URL = xml.rtmp_server;
			        PhoneConfig.APP_NAME = xml.application;
			        var regRequired:String = xml.register_required; 
			        PhoneConfig.REGISTER_REQUIRED = (regRequired == "true");
			    }
			    else
			    {
			        Logger.info("Can not load xml settings. Default settings will be used.");
			    }
			} 
	}
	
	
}